package cn.appsys.controller.appInfoController;

import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.DataDictionary;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.AppCategoryService;
import cn.appsys.service.AppInfoService;
import cn.appsys.service.DataDictionaryService;
import cn.appsys.tools.Constants;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import static cn.appsys.tools.Constants.logoLocPath;
import static cn.appsys.tools.Constants.logoPicPath;

@Controller
@RequestMapping("/appInfo/")
public class AppInfoController {
 private static final Logger logger= Logger.getLogger(AppInfoController.class);
    @Resource
    private AppInfoService appInfoService;
    @Resource
    private AppCategoryService appCategoryService;
    @Resource
     private DataDictionaryService dataDictionaryService;
    @RequestMapping("list")
    public String getAppInfoList(Model model,HttpSession session,
                                 @RequestParam(value="querySoftwareName",required=false) String querySoftwareName,
                                 @RequestParam(value="queryStatus",required=false) String _queryStatus,
                                 @RequestParam(value="queryCategoryLevel1",required=false) String _queryCategoryLevel1,
                                 @RequestParam(value="queryCategoryLevel2",required=false) String _queryCategoryLevel2,
                                 @RequestParam(value="queryCategoryLevel3",required=false) String _queryCategoryLevel3,
                                 @RequestParam(value="queryFlatformId",required=false) String _queryFlatformId
                                ){

        logger.info("getAppInfoList -- > querySoftwareName: " + querySoftwareName);
        logger.info("getAppInfoList -- > queryStatus: " + _queryStatus);
        logger.info("getAppInfoList -- > queryCategoryLevel1: " + _queryCategoryLevel1);
        logger.info("getAppInfoList -- > queryCategoryLevel2: " + _queryCategoryLevel2);
        logger.info("getAppInfoList -- > queryCategoryLevel3: " + _queryCategoryLevel3);
        logger.info("getAppInfoList -- > queryFlatformId: " + _queryFlatformId);


        Integer devId = ((DevUser)session.getAttribute(Constants.DEV_USER_SESSION)).getId();
        List<AppInfo> appInfoList = null;
        List<DataDictionary> statusList = null;
        List<DataDictionary> flatFormList = null;
        List<AppCategory> categoryLevel1List = null;//列出一级分类列表，注：二级和三级分类列表通过异步ajax获取
        List<AppCategory> categoryLevel2List = null;
        List<AppCategory> categoryLevel3List = null;

        Integer queryStatus = null;
        if(_queryStatus != null && !_queryStatus.equals("")){
            queryStatus = Integer.parseInt(_queryStatus);
        }
        Integer queryCategoryLevel1 = null;
        if(_queryCategoryLevel1 != null && !_queryCategoryLevel1.equals("")){
            queryCategoryLevel1 = Integer.parseInt(_queryCategoryLevel1);
        }
        Integer queryCategoryLevel2 = null;
        if(_queryCategoryLevel2 != null && !_queryCategoryLevel2.equals("")){
            queryCategoryLevel2 = Integer.parseInt(_queryCategoryLevel2);
        }
        Integer queryCategoryLevel3 = null;
        if(_queryCategoryLevel3 != null && !_queryCategoryLevel3.equals("")){
            queryCategoryLevel3 = Integer.parseInt(_queryCategoryLevel3);
        }
        Integer queryFlatformId = null;
        if(_queryFlatformId != null && !_queryFlatformId.equals("")){
            queryFlatformId = Integer.parseInt(_queryFlatformId);
        }


        model.addAttribute("appInfoList", appInfoList);
        model.addAttribute("statusList", statusList);
        model.addAttribute("flatFormList", flatFormList);
        model.addAttribute("categoryLevel1List", categoryLevel1List);
        model.addAttribute("queryStatus", queryStatus);
        model.addAttribute("querySoftwareName", querySoftwareName);
        model.addAttribute("queryCategoryLevel1", queryCategoryLevel1);
        model.addAttribute("queryCategoryLevel2", queryCategoryLevel2);
        model.addAttribute("queryCategoryLevel3", queryCategoryLevel3);
        model.addAttribute("queryFlatformId", queryFlatformId);

        //二级分类列表和三级分类列表---回显
        if(queryCategoryLevel2 != null && !queryCategoryLevel2.equals("")){
            categoryLevel2List = getCategoryList(queryCategoryLevel1.toString());
            model.addAttribute("categoryLevel2List", categoryLevel2List);
        }
        if(queryCategoryLevel3 != null && !queryCategoryLevel3.equals("")){
            categoryLevel3List = getCategoryList(queryCategoryLevel2.toString());
            model.addAttribute("categoryLevel3List", categoryLevel3List);
        }
        return "appinfolist";
    }

    public List<DataDictionary> getDataDictionaryList(String typeCode){
        List<DataDictionary> dataDictionaryList = null;
        try {
            dataDictionaryList = dataDictionaryService.getDataDictionaryList(typeCode);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return dataDictionaryList;
    }


     /*根据typeCode查询出相应的数据字典列表*/

    @RequestMapping(value="datadictionarylist",method=RequestMethod.GET)
    @ResponseBody
    public List<DataDictionary> getDataDicList (@RequestParam String tcode){
        logger.debug("getDataDicList tcode ============ " + tcode);
        return this.getDataDictionaryList(tcode);
    }


     /*根据parentId查询出相应的分类级别列表*/

    @RequestMapping(value="categorylevellist",method=RequestMethod.GET)
    @ResponseBody
    public List<AppCategory> getAppCategoryList (@RequestParam String pid){
        logger.debug("getAppCategoryList pid ============ " + pid);
        if(pid.equals("")) pid = null;
        return getCategoryList(pid);
    }
    public List<AppCategory> getCategoryList (String pid){
        List<AppCategory> categoryLevelList = null;
        try {
            categoryLevelList = appCategoryService.getAppCategoryByParentId(pid==null?null:Integer.parseInt(pid));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return categoryLevelList;
    }
   //返回列表页面
    @RequestMapping("appinfo")
    public String appinfo(){
       return "appinfolist";
    }
    //新增页面
    @RequestMapping("add")
    public String addAppInfo(@ModelAttribute("appInfo")AppInfo appInfo, HttpSession session){
         if(null==session.getAttribute(Constants.USER_SESSION)){
           /* return "login";*/
             return "appinfo/appinfoadd";
         }
         return "";
    }
     //保存信息
    @RequestMapping(value = "save",method = RequestMethod.POST)
    public String saveAppInfo(AppInfo appInfo, Model model, HttpSession session, HttpServletRequest request,
                              @RequestParam("a_logoPicPath") MultipartFile multipartFile){
         //取文件名
        String fileName=multipartFile.getOriginalFilename();
        //得到后缀名
        String suffixName = FilenameUtils.getExtension(fileName);
        int filesize = 500000;
        if(multipartFile.getSize()>filesize){
            request.setAttribute("fileError",Constants.FILEUPLOAD_ERROR_4);
            return "appinfo/appinfoadd";
        }
        //匹配文件格式
        if("jpg".equals(suffixName) || "png".equals(suffixName) || "jpeg".equals(suffixName) || "gif".equals(suffixName)) {
            File file = new File(logoLocPath, fileName);//磁盘路径+文件名

            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
                    //写入磁盘
                    multipartFile.transferTo(file);
            } catch (IOException e) {
                request.setAttribute("fileError",Constants.FILEUPLOAD_ERROR_2);
                System.out.println("上传失败原因" + e.getMessage());
                return "appinfo/appinfoadd";
            }
        }else{
            request.setAttribute("fileError",Constants.FILEUPLOAD_ERROR_3);
            return "appinfo/appinfoadd";
            }
        appInfo=(AppInfo)session.getAttribute(Constants.USER_SESSION);
          //加入创建者id
         appInfo.setCreatedBy(appInfo.getCreatedBy());
         //创建日期
        appInfo.setCreationDate(new Date());
        //后台开发者id
       /* appInfo.setDevId(((DevUser)session.getAttribute(Constants.DEV_USER_SESSION)).getId());*/
        //状态默认为1，未审核
        appInfo.setStatus(1);
         //相对路径
        appInfo.setLogoPicPath(logoPicPath+fileName);
        String retCode = "T";
        String retMsg = "上传成功！";
        //返回前台
        model.addAttribute("retCode",retCode);
        model.addAttribute("retMsg",retMsg);

          if(appInfoService.saveAppInfo(appInfo)){
               return "redirect:appinfo";
          }
        return "appinfo/appinfoadd";
    }

    //防重校验
    @RequestMapping(value = "APKExists",method = RequestMethod.GET)
    @ResponseBody
    public String APKExists(@RequestParam("APKName") String APKName){
       AppInfo appInfo=appInfoService.getByAPKName(APKName);
       if(appInfo.getAPKName()==null){
           return "{\"retCode\":\"T\"}";
       }
        return "{\"retCode\":\"F\"}";
    }


}
